package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.WXPAY;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.WebContentActivity;
import com.luoxiang.socialandroid.adapter.TaocancionAdapter;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.TaocanBean;
import com.luoxiang.socialandroid.bean.WechatinfoBean;
import com.luoxiang.socialandroid.bean.ZhifuBaoBean;
import com.luoxiang.socialandroid.common.PayResult;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class SeaPayFragment extends LazyLoadFragment {
    private Button rb_payzhifubao, paybywechat, btn_buycoin;
    private RelativeLayout rl_paybyzhifubao, rl_paybywechat;
    private String paymethod = "ZHIFUBAO";
    private String token;
    private RecyclerView rv_pay_taocan;
    private TaocancionAdapter adapter;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private String order;
    private int charid;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    HashMap<String,String> map = (HashMap<String, String>) msg.obj;
                    PayResult payResult = new PayResult(map);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    LogUtils.i("resultStatus",resultStatus);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtils.showShort("支付成功");
                    } else {
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtils.showShort("支付结果确认中");
                        }
                        else if (TextUtils.equals(resultStatus, "6001")) {
                            ToastUtils.showShort("支付取消");
                        }
                        else if (TextUtils.equals(resultStatus, "6002")) {
                            ToastUtils.showShort("网络异常");
                        }
                        else if (TextUtils.equals(resultStatus, "5000")) {
                            ToastUtils.showShort("重复请求");
                        }
                        else {
                            // 其他值就可以判断为支付失败
                            ToastUtils.showShort("支付失败");
                        }
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected int setContentView() {
        return R.layout.fragment_seachongzhi;
    }

    @Override
    protected void initView() {
        rb_payzhifubao = findViewById(R.id.rb_payzhifubao);
        paybywechat = findViewById(R.id.paybywechat);
        rl_paybyzhifubao = findViewById(R.id.rl_paybyzhifubao);
        rl_paybywechat = findViewById(R.id.rl_paybywechat);
        btn_buycoin = findViewById(R.id.btn_buycoin);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        rv_pay_taocan = findViewById(R.id.rv_pay_taocan);
        initListener();
        getRechargePackages(EXTRA, token, 0);
        LogUtils.i("token", token);
        getRequest();
        Integer wxpay = MmkvUtil.INSTANCE.decodeInt(WXPAY);
        if (wxpay == 0) {
            rl_paybywechat.setVisibility(View.GONE);
        } else {
            rl_paybywechat.setVisibility(View.VISIBLE);

        }
        adapter = new TaocancionAdapter();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        rv_pay_taocan.setLayoutManager(gridLayoutManager);
        btn_buycoin.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if(adapter.list == null || adapter.list.isEmpty()){
                    return;
                }
                if (paymethod.equals("ZHIFUBAO")) {
                    //支付宝支付
                    getRequest();
                    getaffirmRecharge(EXTRA, token, 1, adapter.list.get(adapter.rowindex).getId());

                } else {
                    getRequest();
                    //微信支付
                    getaffirmRecharge(EXTRA, token, 0, adapter.list.get(adapter.rowindex).getId());
                }
            }

            @Override
            protected void onFastClick() {

            }
        });
    }

    private void initListener() {
        rl_paybyzhifubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paybywechat.setBackgroundResource(R.mipmap.bugouxuan);
                rb_payzhifubao.setBackgroundResource(R.mipmap.gouxuan);
                paymethod = "ZHIFUBAO";
            }
        });
        rl_paybywechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paybywechat.setBackgroundResource(R.mipmap.gouxuan);
                rb_payzhifubao.setBackgroundResource(R.mipmap.bugouxuan);
                paymethod = "WECHAT";
            }
        });


    }

    private void getRechargePackages(String extra, String token, int type) {
        NetUtils.getInstance().getApiService().getRechargePackages(extra, token, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr199", decryptStr);
                        Gson gson = new Gson();
                        TaocanBean taocanBean = gson.fromJson(decryptStr, TaocanBean.class);
                        if (taocanBean != null) {
                            if (taocanBean.getData() != null) {
                                adapter.setData(taocanBean.getData().getRecharges());
                                rv_pay_taocan.setAdapter(adapter);
                                charid = taocanBean.getData().getRecharges().get(0).getId();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 微信支付
     *
     * @param extra
     * @param token
     * @param payWay
     * @param packageId
     */
    private void getaffirmRecharge(String extra, String token, int payWay, int packageId) {
        NetUtils.getInstance().getApiService().getaffirmRecharge(extra, token, payWay, packageId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr200", decryptStr);
                        if (paymethod != "ZHIFUBAO") {
                            //不是支付宝就是微信
                            Gson gson = new Gson();
                            WechatinfoBean wechatinfoBean = gson.fromJson(decryptStr, WechatinfoBean.class);

                            if (wechatinfoBean != null) {
                                if (wechatinfoBean.getData() != null) {
                                    IWXAPI api = WXAPIFactory.createWXAPI(getActivity(), wechatinfoBean.getData().getOrder().getAppid());
                                    api.registerApp(wechatinfoBean.getData().getOrder().getAppid());
                                    PayReq payReq = new PayReq();
                                    payReq.appId = wechatinfoBean.getData().getOrder().getAppid();
                                    payReq.partnerId = wechatinfoBean.getData().getOrder().getPartnerid();
                                    payReq.prepayId = wechatinfoBean.getData().getOrder().getPrepayid();
                                    payReq.packageValue = wechatinfoBean.getData().getOrder().getPackage();
                                    payReq.nonceStr = wechatinfoBean.getData().getOrder().getNoncestr();
                                    payReq.timeStamp = wechatinfoBean.getData().getOrder().getTimestamp();
                                    payReq.sign = wechatinfoBean.getData().getOrder().getSign();
                                    boolean b = api.sendReq(payReq);
                                    LogUtils.i("boolean", b);
                                }


//                            IWXAPI api = null;
//
//                            PayReq request = new PayReq();
//
//                            request.appId = wechatinfoBean.getData().getOrder().getAppid();
//
//                            request.partnerId = wechatinfoBean.getData().getOrder().getPartnerid();
//
//                            request.prepayId= wechatinfoBean.getData().getOrder().getPrepayid();
//
//                            request.packageValue = wechatinfoBean.getData().getOrder().getPackage();
//
//                            request.nonceStr= wechatinfoBean.getData().getOrder().getNoncestr();
//
//                            request.timeStamp= wechatinfoBean.getData().getOrder().getTimestamp();
//
//                            request.sign= wechatinfoBean.getData().getOrder().getSign();
//
//                            api.sendReq(request);
                            }
                        } else if (paymethod == "ZHIFUBAO") {
                            Gson gson1 = new Gson();
                            ZhifuBaoBean zhifuBaoBean = gson1.fromJson(decryptStr, ZhifuBaoBean.class);
                            int payPattern = zhifuBaoBean.getData().getPayPattern();
                            if (zhifuBaoBean != null) {
                                if (zhifuBaoBean.getData() != null) {
                                    if (zhifuBaoBean.getData().getOrder() != null) {
                                        order = zhifuBaoBean.getData().getOrder();//订单信息

                                    }
                                }
                            }
                            if (payPattern == 0) {

                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(getActivity());
                                        Map<String, String> result = alipay.payV2(order, true);
                                        LogUtils.i("orders", order);
                                        Message msg = new Message();
                                        msg.what = SDK_PAY_FLAG;
                                        msg.obj = result;
                                        mHandler.sendMessage(msg);
                                    }
                                };
                                // 必须异步调用
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            } else {
                                Intent intent = new Intent(getContext(), WebContentActivity.class);

                                String s = order.replaceAll("\u003d", "=").replaceAll("\u0026", "&");
                                LogUtils.i("ssssdd", s);
                                intent.putExtra("h5url", s);
                                startActivity(intent);
                            }


                        }


                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void lazyLoad() {

    }
}
